package org.web.tablesqlcheck.server.biz;

import com.alibaba.druid.DbType;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.web.base.domain.ResultDO;
import org.web.base.domain.helper.ValidationHelper;
import org.web.tablesqlcheck.sdk.dto.*;
import org.web.tablesqlcheck.server.domain.TableDefinitionRuleDO;
import org.web.tablesqlcheck.server.domain.query.QueryTableDefinitionRule;
import org.web.tablesqlcheck.server.service.TableDefinitionRuleService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("tableSqlCheckBiz")
public class TableSqlCheckBiz implements TableSqlCheckConstant {

    @Resource
    private TableDefinitionRuleService tableDefinitionRuleService;

    public ResultDO<List<CheckRuleTaskDTO>> checkSql(SqlCheckRequest sqlCheckDTO) {
        ResultDO<List<CheckRuleTaskDTO>> resultDO = new ResultDO();
        try {
            ValidationHelper.validateWithThrow(SqlCheckRequest.class, sqlCheckDTO);
            QueryTableDefinitionRule queryTableDefinitionRule = new QueryTableDefinitionRule();
            List<Short> severityLevelList = sqlCheckDTO.getSeverityLevelList();
            if (ObjectUtils.isNotEmpty(severityLevelList)) {
                queryTableDefinitionRule.setSeverityLevelList(severityLevelList);
            }
            queryTableDefinitionRule.setRuleStatus(STATUS.ON.name());
            List<TableDefinitionRuleDO> tableDefinitionRuleDOList = tableDefinitionRuleService.selectTableDefinitionRuleList(queryTableDefinitionRule);
            List<String> sqlList = sqlCheckDTO.getBuildSqlList();
            List<TableInfoDTO> tableInfoDTOList = new ArrayList<>();
            for (String sql : sqlList) {
                TableInfoDTO tableInfoDTO = TableSqlCheckHelper.parseByTableType(sql, DbType.mysql);
                tableInfoDTOList.add(tableInfoDTO);
            }

//            List<CheckRuleDTO> checkRuleDTOList = new ArrayList<>();
//            for (TableDefinitionRuleDO tableDefinitionRuleDO : tableDefinitionRuleDOList) {
//                RuleCheckRequest sqlRuleCheckRequest = new RuleCheckRequest();
//                BeanUtils.copyProperties(checkRuleDTOList, tableDefinitionRuleDO);
//                ruleCheckRequestList.add(sqlRuleCheckRequest);
//            }

            for (TableInfoDTO tableInfoDTO : tableInfoDTOList) {
                // CheckTaskRequest（SqlRuleCheckRequest + TableInfoDTO） => CheckResultDTO
                // CheckBuildSqlListRequest checkBuildSqlListRequest = new CheckBuildSqlListRequest(ruleCheckRequestList, tableInfoDTO);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultDO;
    }

}
